<?php

namespace App\Services\Dao;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\User;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Collection;
use Hyperf\Database\Model\Model;

class UserDao
{
    /**
     * @param string $username
     * @return Builder|Model|object|null
     */
    public function findByUserName(string $username)
    {
        return User::query()->where('username','=', $username)->first();
    }

    /**
     * @param int $id
     * @param bool $throw
     * @return null|User
     */
    public function first(int $id, bool $throw=false)
    {
        $model = User::query()->find($id);
        if (empty($model) && $throw) {
            throw new BusinessException(ErrorCode::USER_NOT_EXIST, ErrorCode::getMessage(ErrorCode::USER_NOT_EXIST));
        }
        return $model;
    }

    /**
     * @param string $phone
     * @return Builder|Model|object|null
     */
    public function findByPhone(string $phone)
    {
        return User::query()->where('phone', '=', $phone)->first();
    }
}